package com.st.warehouse.ui.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.st.warehouse.R;
import com.st.warehouse.utils.Data;
import com.st.warehouse.utils.DialogUtils;
import com.st.warehouse.utils.HttpClientUtils;
import com.st.warehouse.utils.HttpRequestUtils;
import com.st.warehouse.utils.RegexUtils;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

//登录界面
public class LoginActivity extends AppCompatActivity {

    private EditText input_account;
    private EditText input_password;
    private EditText input_phone;
    private EditText input_code;
    private TextView tv_to_phone;
    private TextView tv_account;
    private Button btn_send_code;
    private LinearLayout ll_login_account;
    private LinearLayout ll_login_phone;
    private CountDownTimer countDownTimer;
    private boolean isCountingDown = false;
    private Button btn_login_account;
    private Button btn_login_phone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //初始化
        initView();
    }

    private void initView() {
        //状态栏设置
        getWindow().setStatusBarColor(getColor(R.color.transparent));
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//字体黑色
        getSupportActionBar().hide();//隐藏标题栏
        //
        ll_login_account = findViewById(R.id.ll_login_account);//账号密码登录视图区
        ll_login_phone = findViewById(R.id.ll_login_phone);//手机号登录视图区
        tv_to_phone = findViewById(R.id.tv_to_phone);//手机号登录
        tv_account = findViewById(R.id.tv_account);//账号密码登录
        btn_send_code = findViewById(R.id.btn_send_code);//账号密码登录
        //
        input_account = findViewById(R.id.input_account);//用户名
        input_password = findViewById(R.id.input_password);//密码
        input_phone = findViewById(R.id.input_phone);//手机号
        input_code = findViewById(R.id.input_code);//验证码
        //
        btn_login_phone = findViewById(R.id.btn_login_phone);//手机号登录
        listener();
    }
    final int DRAWABLE_RIGHT = 2;//左：0,上：1,右：2,下：3
    boolean isPasswordVisible = false; // 记录密码是否可见

    /**
     * 监听事件
     */
    @SuppressLint("ClickableViewAccessibility")
    private void listener() {

        // 监听密码显示/隐藏切换按钮的点击事件
        input_password.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (event.getRawX() >= (input_password.getRight() - input_password.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width()/2)) {
                        // 点击了右侧图标
                        isPasswordVisible = !isPasswordVisible; // 切换密码可见状态

                        if (isPasswordVisible) {
                            // 显示明文
                            input_password.setInputType(InputType.TYPE_CLASS_TEXT);
                            input_password.setCompoundDrawablesWithIntrinsicBounds(R.drawable.shape_icon_password, 0, R.drawable.shape_icon_password_show, 0);
                        } else {
                            // 显示密文
                            input_password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                            input_password.setCompoundDrawablesWithIntrinsicBounds(R.drawable.shape_icon_password, 0, R.drawable.shape_icon_password_unshow, 0);
                        }
                        // 将光标移动到末尾
                        input_password.setSelection(input_password.getText().length());
                        return true;
                    }
                }
                return false;
            }
        });

        //跳转手机号登录
        tv_to_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ll_login_phone.setVisibility(View.VISIBLE);
                ll_login_account.setVisibility(View.GONE);
            }
        });

        //跳转账号登录
        tv_account.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ll_login_phone.setVisibility(View.GONE);
                ll_login_account.setVisibility(View.VISIBLE);
            }
        });

    }

    /**
     * 手机号登录
     * @param phone
     * @param code
     */
    private void phoneLogin(String phone, String code) {
        String getUrl = "/app/user/login";
        RequestBody formBody = new FormBody.Builder()
                .add("phone", phone)
                .add("code", code)
                .build();
        HttpRequestUtils.post(getUrl, formBody, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                DialogUtils.show(LoginActivity.this, "网络异常,请联系管理员");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                JSONObject result = HttpRequestUtils.result(response);
                if ("200".equals(result.getString("code"))){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            DialogUtils.show(LoginActivity.this, "登录成功");
                        }
                    });

                }
            }
        });
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HttpClientUtils.MSG_WHAT_LOGIN_SUCCESS: {      // 登录成功
                    JSONObject data = (JSONObject) msg.obj;
                    //登录返回的结果

                    break;
                }

            }
        }
    };

    /**
     * 发送验证码
     */
    private void sendCode() {
        String phone = input_phone.getText().toString();
        String getUrl = "/app/user/code";
        JSONObject reqJson = new JSONObject();
        reqJson.put("phone", phone);

        // 创建请求体，这里我们发送的是表单数据，所以使用FormBody
        RequestBody formBody = new FormBody.Builder()
                .add("phone", phone)
                .build();
        // 这里是发送验证码请求的代码，比如通过网络请求发送短信
        Toast.makeText(this, "验证码已发送", Toast.LENGTH_SHORT).show();
        HttpRequestUtils.post(getUrl, formBody, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (e instanceof SocketTimeoutException) {
                    Toast.makeText(LoginActivity.this, "请求超时", Toast.LENGTH_SHORT).show();
                } else if (e instanceof ConnectException) {
                    Toast.makeText(LoginActivity.this, "连接异常", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(LoginActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                JSONObject result = HttpRequestUtils.result(response);
                if ("200".equals(result.getString("code"))){
                    JSONObject data = Data.getJSONObject(result, "data", new JSONObject());
                    String string = data.getString("phoneCode");
                    //Toast.makeText(LoginActivity.this, "请求成功，验证码为:", Toast.LENGTH_SHORT).show();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(LoginActivity.this, "请求成功，验证码为:"+string, Toast.LENGTH_SHORT).show();
                        }
                    });

                }
            }
        });
        //HttpClientUtils.senCode(mHandler);

    }


    /**
     * 倒计时60s
     */
    private void startCountDownTimer() {
        isCountingDown = true;
        countDownTimer = new CountDownTimer(60000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                // 更新按钮文本为倒计时时间
                btn_send_code.setText(String.format("%d秒", millisUntilFinished / 1000));
                btn_send_code.setEnabled(false); // 禁用按钮
            }

            @Override
            public void onFinish() {
                // 倒计时结束，恢复按钮状态
                btn_send_code.setText("发送验证码");
                btn_send_code.setEnabled(true);
                isCountingDown = false;
            }
        }.start();
    }

    /**
     * 账号密码登录
     * @param view
     */
    public void accountLogin(View view) {
        String account = input_account.getText().toString();
        String password = input_password.getText().toString();
        if (Data.isNull(account.trim()) || Data.isNull(password)){
            DialogUtils.show(LoginActivity.this,"请输入账号密码");
        }
        //todo：登录
    }

    /**
     * 发送短信验证码
     * @param view
     */
    public void sendCode(View view) {
        String userPhone = input_phone.getText().toString();
        if (Data.isNull(userPhone)) {
            Toast.makeText(LoginActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (RegexUtils.isPhoneInvalid(userPhone)){
            Toast.makeText(LoginActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!isCountingDown) {
            sendCode();// 发送验证码
            startCountDownTimer();// 开始倒计时
        }
    }

    /**
     * 短信登陆
     * @param view
     */
    public void phoneLogin(View view) {
        String phone = input_phone.getText().toString();
        String code = input_code.getText().toString();
        if (Data.isNull(phone)) {
            DialogUtils.show(LoginActivity.this, "请输入手机号");
        }
        if (Data.isNull(code)) {
            DialogUtils.show(LoginActivity.this, "请输入验证码");
        }
        //
        phoneLogin(phone, code);
    }
}